package com.newsnetwork.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.newsnetwork.admin.mapper.AdminUserMapper;
import com.newsnetwork.admin.service.AdminUserService;
import com.newsnetwork.exception.GraceException;
import com.newsnetwork.grace.result.ResponseStatusEnum;
import com.newsnetwork.pojo.AdminUser;
import com.newsnetwork.pojo.bo.NewAdminBO;
import com.newsnetwork.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author: HuangDekai
 * @date: 2022/11/7 11:13
 * @version: 1.0
 * @since: jdk8
 * @description: 管理员用户的 service 的实现类
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private Sid sid;


    /**
     * 根据"管理员用户名"，查询管理员用户；
     * 所以，在admin_user表中，我们要保证username字段的唯一；即管理员用户不允许重名；
     *
     * @param username 用户名
     * @return
     */
    @Override
    public AdminUser queryAdminByUsername(String username) {

        //1.利用tkmybatis的Example，自定义查询条件；
        // 1.1先创建一个查询实例，这个实例，是针对AdminUser作查询的；
        Example adminExample = new Example(AdminUser.class);
        // 1.2给上面的查询实例，增加查询条件；
        Example.Criteria criteria = adminExample.createCriteria();
        //第一个参数：AdminUser实体类中的username；第二个参数：queryAdminByUsername这个方法的username参数；
        criteria.andEqualTo("username", username);

        //2.利用创建好的查询条件，调用方法，去查数据库；
        AdminUser adminUser = adminUserMapper.selectOneByExample(adminExample);
        return adminUser;
    }

    /**
     * 新增管理员
     *
     * @param newAdminBO 增新管理员BO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createAdminUser(NewAdminBO newAdminBO) {
        String adminId = sid.nextShort();
        AdminUser adminUser = new AdminUser();
        adminUser.setId(adminId);
        adminUser.setUsername(newAdminBO.getUsername());
        adminUser.setAdminName(newAdminBO.getAdminName());

        // 如果密码不为空, 加密密码存入数据库
        if (StringUtils.isNotBlank(newAdminBO.getPassword())) {
            String pwd = BCrypt.hashpw(newAdminBO.getPassword(), BCrypt.gensalt());
            adminUser.setPassword(pwd);
        }

        // 如果传入了人脸图片, 有 faceId
        if (StringUtils.isNotBlank(newAdminBO.getFaceId())) {
            adminUser.setFaceId(newAdminBO.getFaceId());
        }

        adminUser.setCreatedTime(new Date());
        adminUser.setUpdatedTime(new Date());

        int insert = adminUserMapper.insert(adminUser);

        if (insert != 1) {
            GraceException.display(ResponseStatusEnum.ADMIN_CREATE_ERROR);
        }
    }

    /**
     * 分页查询 admin
     *
     * @param page     第几页 (从 1 开始)
     * @param pageSize 每页有几条数据
     */
    @Override
    public PagedGridResult queryAdminList(Integer page, Integer pageSize) {
        Example adminExample = new Example(AdminUser.class);
        adminExample.orderBy("createdTime").desc();

        // 启用分页插件, 在查询之前进行拦截, 进行分页
        PageHelper.startPage(page, pageSize);
        List<AdminUser> adminUserList = adminUserMapper.selectByExample(adminExample);

        return setterPagedGrid(adminUserList, page);
    }

    /**
     * 将 adminUserList 做一个 分页 封装
     * @param adminUserList 管理员用户列表
     * @param page 分页中的第几页
     * @return 分页封装好的 adminUserList
     */
    private PagedGridResult setterPagedGrid(List<?> adminUserList,
                                            Integer page) {
        PageInfo<?> pageList = new PageInfo<>(adminUserList);
        PagedGridResult gridResult = new PagedGridResult();
        gridResult.setRows(adminUserList);
        gridResult.setPage(page);
        //总页数, 由分页插件计算
        gridResult.setRecords(pageList.getPages());
        //总记录数
        gridResult.setTotal(pageList.getTotal());

        return gridResult;
    }
}
